package io.gitee.zhangbinhub.acp.cloud.resource.server

import io.gitee.zhangbinhub.acp.boot.tools.EnvironmentTools
import io.gitee.zhangbinhub.acp.cloud.resource.server.constant.AcpCloudResourceServerConstant
import org.springframework.boot.SpringApplication
import org.springframework.boot.env.EnvironmentPostProcessor
import org.springframework.core.env.ConfigurableEnvironment

/**
 * 资源服务自动配置
 *
 * @since JDK 17
 */
class AcpCloudResourceServerEnvironmentPostProcessor : EnvironmentPostProcessor {
    private val defaultPropertiesName = "acpCloudResourceServerOverridesProperties"
    private val clientIdProperty = "${AcpCloudResourceServerConstant.PROPERTIES_PREFIX}.client-id"
    private val clientSecretProperty = "${AcpCloudResourceServerConstant.PROPERTIES_PREFIX}.client-secret"
    private val defaultClientId = AcpCloudResourceServerConstant.CLIENT_ID
    private val defaultClientSecret = AcpCloudResourceServerConstant.CLIENT_SECRET

    override fun postProcessEnvironment(environment: ConfigurableEnvironment?, application: SpringApplication?) {
        val default: MutableMap<String, Any> = HashMap()
        var clientId = defaultClientId
        var clientSecret = defaultClientSecret
        if (environment!!.containsProperty(clientIdProperty)) {
            clientId = environment.getProperty(clientIdProperty, defaultClientId)
        }
        if (environment.containsProperty(clientSecretProperty)) {
            clientSecret = environment.getProperty(clientSecretProperty, defaultClientSecret)
        }
        default[clientIdProperty] = clientId
        default[clientSecretProperty] = clientSecret
        EnvironmentTools.addOrReplaceProperty(environment.propertySources, default, defaultPropertiesName, false)
    }
}
